// (c)2016 Flipboard Inc, All Rights Reserved.

package com.jpyl.jpMedicalTreatment.network;


import android.util.Log;

import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.PreferenceKit;
import com.google.gson.Gson;
import com.jpyl.jpMedicalTreatment.MedicalApplication;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class Network {

    private static RequestApi requestApi;
    private static RequestApi requestApiWithoutConverter;
//    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
//            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
//            .connectTimeout(30, TimeUnit.SECONDS)
//            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
//            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
//            .build();

    private static OkHttpClient okHttpClient = getClient();
    private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create(new Gson());
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();

    public static RequestApi getRequestApi() {
//        if (requestApi == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(Const.PROTOCOL + Const.IP + "/")
                    .addConverterFactory(gsonConverterFactory)
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .build();
            requestApi = retrofit.create(RequestApi.class);
//        }
        return requestApi;
    }

    public static RequestApi getRequestApiWithoutConverter() {
        if (requestApiWithoutConverter == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(Const.PROTOCOL + Const.IP + "/")
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .build();
            requestApiWithoutConverter = retrofit.create(RequestApi.class);
        }
        return requestApiWithoutConverter;
    }

    /**
     * 初始化 OkHttpClient
     *
     * @return
     */
    private static OkHttpClient getClient() {
        OkHttpClient.Builder client = new OkHttpClient().newBuilder();

        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // 获取 Cookie
                Response resp = chain.proceed(chain.request());
                List<String> cookies = resp.headers("Set-Cookie");
                String cookieStr = "";
                if (cookies != null && cookies.size() > 0) {
                    for (int i = 0; i < cookies.size(); i++) {
//                        Log.e("Actiivty","===i==="+i+"===cookies.get(i)====="+cookies.get(i));
                        cookieStr += cookies.get(i);
                    }
                    PreferenceKit.setSharedPreference(MedicalApplication.applicationContext, MedicalSettings.MEMBER_COOKIE, cookieStr);
                }
                return resp;
            }
        });

        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // 设置 Cookie
                String cookieStr = PreferenceKit.getSharedPreference(MedicalApplication.applicationContext, MedicalSettings.MEMBER_COOKIE, "");
                if(!JavaKit.isStringEmpty(cookieStr)){
                    return chain.proceed(chain.request().newBuilder().header("Cookie", cookieStr).build());
                }
                return chain.proceed(chain.request());
            }
        });
        client.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        client.connectTimeout(30, TimeUnit.SECONDS);
        client.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        client.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        return client.build();
    }
}
